package com.fleafinder;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;

 public class Facebook {

	 public static void LogIn(final Activity activity)
	 {
		 Session.openActiveSession(activity, true, new Session.StatusCallback() {
				@Override
				public void call(Session session, SessionState state,
						Exception exception) {
					if (session.isOpened()) {
						Request.executeMeRequestAsync(session,
								new Request.GraphUserCallback() {
									@Override
									public void onCompleted(GraphUser user,
											Response response) {
										if (user != null) {
//											System.out.println("Facebook user logged in");
											Share(activity);
										}
									}
								});
					}
				}
			});
	 }
	 
	 public static void LogOut()
	 {
		 Session s = Session.getActiveSession();
		 if(s != null){
			 s.closeAndClearTokenInformation();
		 }
	 }
	 
	 public static void Share(Context context)
	 {
		 Session s = Session.getActiveSession();
		
		 Bundle params = new Bundle();
			params.putString("name", context.getResources().getString(R.string.facebook_name));
			params.putString("caption", context.getResources().getString(R.string.facebook_name));
			params.putString("description", context.getResources().getString(R.string.facebook_description));
			params.putString("link", CommonConstants.LINK_WEBSITE);
			params.putString("picture", CommonConstants.LINK_PRODUCTS_ON_WEBSITE);
			
			WebDialog.FeedDialogBuilder feedDialog = (new WebDialog.FeedDialogBuilder(context, s, params));
			feedDialog.setOnCompleteListener(new WebDialog.OnCompleteListener() {
				
				@Override
				public void onComplete(Bundle values, FacebookException error) {
					if(error == null){
						final String postId = values.getString("post_id");
						if(postId != null){
//							System.out.println("Feed posted");
							Log.d("fleafinder", "Feed Posted");
						} else {
//							System.out.println("Feed failed");
							Log.d("fleafinder", "Feed failed");
						}
					} else if(error instanceof FacebookOperationCanceledException){
//						System.out.println("Feed failed");		
						Log.d("fleafinder", error.getMessage());
					} else {
						error.printStackTrace();
					}
				}
			});
			
			feedDialog.build().show();
	 }
}
